package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.community.ComUserRelation;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.UserInfo;
import com.maiji.cloud.entities.manager.User;
import com.maiji.cloud.mapper.ComUserRelationMapper;
import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.request.BaseInputDto;
import com.maiji.cloud.request.IdInputDto;
import com.maiji.cloud.request.community.ComUserMessageInputDto;
import com.maiji.cloud.request.community.ComUserRelationInputDto;
import com.maiji.cloud.response.BaseOutPutDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.login.UserInfoResData;
import com.maiji.cloud.service.AsyncService;
import com.maiji.cloud.service.ComUserRelationService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.utils.ComUserMessageTypeEnum;
import com.maiji.cloud.utils.RedisUtil;
import com.maiji.cloud.utils.TimeUtil;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2019-07-04
 */
@Service
@Transactional
public class ComUserRelationServiceImpl extends ServiceImpl<ComUserRelationMapper,ComUserRelation> implements ComUserRelationService {

    @Autowired
    ComUserRelationMapper userRelationMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 关注用户
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<String> focusUser(@RequestBody BaseInputDto<IdInputDto> inputDto, @RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<String> outPutDto = new BaseOutPutDto<>();
        try{

            //        获取访问用户ID
            AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
            String userId = appUser.getUuId();
            if(userId.equals(inputDto.getData().getId())){
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("不能关注自己");
                return outPutDto;

            }
            ComUserRelation userRelation =new ComUserRelation();
            userRelation.setFollowerId(userId);
            userRelation.setType(0);
            userRelation.setFocuserId(inputDto.getData().getId());
            userRelation.setFollowTime(TimeUtil.getCurDateStamp());

            {
                ComUserRelation newUserRelation = new ComUserRelation();
                newUserRelation.setFocuserId(userRelation.getFollowerId());
                newUserRelation.setFollowerId(userRelation.getFocuserId());
                ComUserRelation relation = userRelationMapper.selectOne(newUserRelation);
                if(relation!= null){
                    //判断是否是互粉丝关系
                    userRelation.setType(1);
                    relation.setType(1);
                    //修改 关注关系
                    EntityWrapper<ComUserRelation> entityWrapper = new EntityWrapper();
                    entityWrapper.setEntity(newUserRelation);
                    userRelationMapper.update(relation,entityWrapper);
                }
            }

            if(userRelationMapper.insert(userRelation)>0){
                outPutDto.setStatus(Status.SUCCESS);
                outPutDto.setMessage("关注成功");

                {
                    ComUserMessageInputDto messageInputDto = new ComUserMessageInputDto();
                    messageInputDto.setContent("关注了你");
                    messageInputDto.setSourceUserId(userId);
                    messageInputDto.setTargetUserId(userRelation.getFocuserId());
                    messageInputDto.setType(ComUserMessageTypeEnum.Follow.getValue());
                    asyncService.asycCreateMessage(messageInputDto);

                }

            }else{
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("关注失败");
            }
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
            return outPutDto;
        }

    }


    /**
     * 取消关注用户
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<String> cancelFocusUser(@RequestBody BaseInputDto<IdInputDto> inputDto, @RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<String> outPutDto = new BaseOutPutDto<>();

        //        获取访问用户ID
        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();
        try{

            ComUserRelation userRelation =new ComUserRelation();
            userRelation.setFollowerId(userId);
            userRelation.setFocuserId(inputDto.getData().getId());


            EntityWrapper<ComUserRelation> discountCouponEntityWrapper = new EntityWrapper<>();
            discountCouponEntityWrapper.setEntity(userRelation);

            if(userRelationMapper.delete(discountCouponEntityWrapper) >0){

                {
                    //判断是否是互粉关系 是则取消
                    ComUserRelation newUserRelation = new ComUserRelation();
                    newUserRelation.setFocuserId(userRelation.getFollowerId());
                    newUserRelation.setFollowerId(userRelation.getFocuserId());
                    newUserRelation = userRelationMapper.selectOne(newUserRelation);
                    if(newUserRelation != null){
                        userRelationMapper.update(new ComUserRelation().setType(0),new EntityWrapper<ComUserRelation>(newUserRelation));
                    }
                }

                outPutDto.setStatus(Status.SUCCESS);
                outPutDto.setMessage("取消成功");
            }else{
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("取消失败");
            }
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
            return outPutDto;
        }

    }


    /**
     * 用户关注列表
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<List<UserInfoResData>>focuserList(@RequestBody BaseInputDto<ComUserRelationInputDto> inputDto , @RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<List< UserInfoResData>> outPutDto = new BaseOutPutDto<>();

        try{

            //        获取访问用户ID
            AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
            String userId = appUser.getUuId();

//            List<UserInfo> userRelations = userRelationMapper.findAllUserInfoByFId(userId);
//            List<UserInfoResData> userInfoResDatas = new ArrayList<>();
//            for (UserInfo userInfo:userRelations
//                 ) {
//                UserInfoResData data = new UserInfoResData();
//                BeanUtils.copyProperties(userInfo,data);
//                userInfoResDatas.add(data);
//            }
            outPutDto.setData(getUserRelationList(userId,null
                    ,inputDto.getMetaData().getPage(),inputDto.getMetaData().getSize(),true));
            outPutDto.setStatus(Status.SUCCESS);
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
            return outPutDto;
        }

    }

    /**
     * 用户粉丝列表
     * @param inputDto
     * @param maijiToken
     * @return
     */

    public BaseOutPutDto<List<UserInfoResData>>followerList(@RequestBody BaseInputDto<ComUserRelationInputDto> inputDto , @RequestHeader("maijiToken")String maijiToken){
        BaseOutPutDto<List< UserInfoResData>> outPutDto = new BaseOutPutDto<>();

        try{
            //        获取访问用户ID
            AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
            String userId = appUser.getUuId();


            outPutDto.setData(getUserRelationList(null,userId,inputDto.getMetaData().getPage(),inputDto.getMetaData().getSize(),false));
            outPutDto.setStatus(Status.SUCCESS);
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
            return outPutDto;
        }

    }

    private List<UserInfoResData> getUserRelationList(String followerId , String focuserId , Integer pageNo , Integer size , Boolean isFocuserList){
        EntityWrapper<ComUserRelation> entityWrapper = new EntityWrapper<>();
        ComUserRelation userRelation = new ComUserRelation();
        Function<ComUserRelation, String> mapper = ComUserRelation::getFocuserId;
        if(followerId != null){
            userRelation.setFollowerId(followerId);
            mapper = ComUserRelation::getFocuserId;
        }
        if(focuserId != null){
            userRelation.setFocuserId(focuserId);
            mapper = ComUserRelation::getFollowerId;
        }
        entityWrapper.setEntity(userRelation);
        entityWrapper.orderBy("type",false).and().orderBy("follow_time",false);
        Page<ComUserRelation> page = new Page<>(pageNo,size);
        return reloadUserRelationList(userRelationMapper.selectPage(page,entityWrapper),mapper,isFocuserList);
    }

    private List<UserInfoResData> reloadUserRelationList(List<ComUserRelation> userRelations , Function<ComUserRelation, String> mapper,Boolean isFocuserList){
        List<ComUserRelation> allList = userRelations;

        List<ComUserRelation> friendList = new ArrayList<>();
        List<ComUserRelation> normalList = new ArrayList<>();
        for (ComUserRelation ur:allList
        ) {
            if(ur.getType() == 1){
                friendList.add(ur);
            }else{
                normalList.add(ur);
            }
        }

        List<UserInfoResData> allUserInfos = new ArrayList<>();

        if(friendList != null && friendList.size() > 0){
            List<String> friendUserIds = friendList.parallelStream().map(mapper).collect(Collectors.toList());
            HashMap<String, Object> map1 = Maps.newHashMap();
            map1.put("userIds", friendUserIds);
            List<UserInfo> followerUsers = userInfoService.selectList(map1);
            for (UserInfo ui:followerUsers
            ) {
                UserInfoResData userInfoResData = new UserInfoResData();
                BeanUtils.copyProperties(ui,userInfoResData);
                userInfoResData.setIsFollow(true);
                allUserInfos.add(userInfoResData);
            }
        }
        if(normalList != null && normalList.size() > 0){
            List<String> normalUserIds = normalList.parallelStream().map(mapper).collect(Collectors.toList());
            HashMap<String, Object> map2 = Maps.newHashMap();
            map2.put("userIds", normalUserIds);
            List<UserInfo> normalUsers = userInfoService.selectList(map2);
            for (UserInfo ui : normalUsers){
                UserInfoResData userInfoResData = new UserInfoResData();
                BeanUtils.copyProperties(ui,userInfoResData);
                userInfoResData.setIsFollow(isFocuserList);
                allUserInfos.add(userInfoResData);
            }
        }
        return allUserInfos;
    }


	@Override
	public BaseOutPutDto<Boolean> isFocusUser(String userId, String maijiToken) {
		  AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
		  
		  if(appUser == null || StringUtils.isBlank(appUser.getUuId()) || StringUtils.isBlank(userId)) return new BaseOutPutDto<Boolean>(Status.PWDOLDERROR);
          ComUserRelation entity = new ComUserRelation();
          entity.setFocuserId(userId);
          entity.setFollowerId(appUser.getUuId());
          
          ComUserRelation newEntity = userRelationMapper.selectOne(entity);
          
          BaseOutPutDto<Boolean> baseOutPutDto = new BaseOutPutDto<Boolean>(Status.SUCCESS);
          if(newEntity == null)baseOutPutDto.setData(false);
          else baseOutPutDto.setData(true);
          
		return baseOutPutDto;
	}

}
